﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.IdentityModel.Protocols.WSFederation;
using System.Web.Security;

namespace Veracruz.Facebook.Web
{
    public sealed class FacebookCallbackHandler : IHttpHandler
    {
        #region ctors

        public FacebookCallbackHandler()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #endregion
        #region methods

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string l_auth_token = context.Request[Constants.AuthentificationToken];
            string l_installed = context.Request[Constants.Installed];
            string l_returnUrl = context.Request[Constants.ReturnUrl];
            string l_realm = context.Request[WSFederationConstants.Parameters.Realm];
            string l_action = context.Request[WSFederationConstants.Parameters.Action];

            if (l_auth_token == null)
            {
                throw new NotImplementedException();
            }
            else
            {
                // HACK : Remove the Forms authentication using.
                FormsAuthentication.SetAuthCookie(l_auth_token, false);
                
                string l_url = string.Format("{0}?{1}={2}&{3}={4}&{5}={6}", 
                    l_returnUrl,
                    Constants.AuthentificationToken, l_auth_token, 
                    WSFederationConstants.Parameters.Realm, l_realm,
                    WSFederationConstants.Parameters.Action, l_action);

                context.Response.Redirect(l_url);
            }
        }

        #endregion
    }
}
